﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using TiaoTiaoCode.AutoUpdate.Common.Exceptions;

namespace TiaoTiaoCode.AutoUpdate.WebApi.Filters
{
    /// <summary>
    /// Api服务异常捕获处理
    /// </summary>
    public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 异常处理方法
        /// </summary>
        /// <param name="context">异常上下文</param>
        public override void OnException(ExceptionContext context)
        {
            context.Result = ExceptionResult(context.Exception);

            base.OnException(context);
        }

        /// <summary>
        /// 异常返回
        /// </summary>
        /// <param name="ex">异常</param>
        /// <returns>返回</returns>
        public IActionResult ExceptionResult(Exception ex)
        {
            if (ex is CustomException cex)
                return new JsonResult(new { IsSuccess = false, code = cex.Code, Message = ex.Message });

            if (ex is ApplicationException)
                return new JsonResult(new { IsSucces = false, Code = 501, Message = ex.Message });

            return new JsonResult(new { IsSucces = false, Code = 500, Message = ex.Message, InnerMessage = "系统内部异常" });
        }
    }
}
